import React, { useEffect, useRef, useState } from 'react';

import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import { useAppSelector } from '@/store';
import io, { Socket } from 'socket.io-client';
import { getToken } from '@/utils/storage';
import { baseURL } from '@/utils/request';
import { Toast } from 'antd-mobile';

export default function Chat() {
  const { userInfo } = useAppSelector((state) => state.user);

  const [msg, setMsg] = useState('');
  type MsgType = {
    type: string;
    msg: string;
    timestamp: number;
  };
  // 聊天记录
  const [messageList, setMessageList] = useState<MsgType[]>([
    // 放两条初始消息
    {
      type: 'robot',
      msg: '亲爱的用户您好，小智同学为您服务。',
      timestamp: Date.now(),
    },
    { type: 'user', msg: '你好', timestamp: Date.now() },
  ]);

  //用于缓存
  const clientRef = useRef(null as unknown as Socket);
  const handleSend = () => {
    if (msg.trim()) {
      //发送消息
      clientRef.current.emit('message', { msg, timestamp: Date.now() });
      setMessageList((messageList) => [
        ...messageList,
        { type: 'user', msg, timestamp: Date.now() },
      ]);
      setMsg('');
    } else {
      Toast.show({ content: '不能发送空消息', duration: 1000 });
    }
  };
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSend();
    }
  };

  useEffect(() => {
    //创建客户端实例
    const client = io(baseURL, {
      query: { token: getToken().token },
      transports: ['websocket'],
    });
    console.log(client);

    //监听链接成功的事件
    client.on('connect', () => {
      console.log(6666);

      setMessageList((messageList) => [
        ...messageList,
        { type: 'robot', msg: '我现在恭候着您的提问。', timestamp: Date.now() },
      ]);
    });
    //监听收到消息的事件
    client.on('message', (data) => {
      console.log(data);
      setMessageList((messageList) => [
        ...messageList,
        { type: 'robot', ...data },
      ]);
    });

    clientRef.current = client;
    // 卸载时关闭连接;
    return () => {
      client.close();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 监听聊天数据的变化，改变聊天容器元素的 scrollTop 值让页面滚到最底部
  useEffect(() => {
    window.scrollTo({
      // 页面有多高，就滚动多少
      top: document.body.scrollHeight, //scrollHeight指不可见的，超出的高度
      // behavior: 'smooth', 平滑滚动
      behavior: 'smooth',
    });
  }, [messageList]);
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>小智同学</NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list">
        {messageList.map((item, index) => {
          return item.type === 'robot' ? (
            <div className="chat-item" key={index}>
              <Icon type="iconbtn_xiaozhitongxue" />
              <div className="message">{item.msg}</div>
            </div>
          ) : (
            <div className="chat-item user" key={index}>
              <img src={userInfo.photo} alt="" />
              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="footer">
        <div className="input-footer">
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            onKeyDown={(e) => handleKeyDown(e)}
          />
          <Icon type="iconbianji" />
          <span className="send" onClick={() => handleSend()}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
